<?php
namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\AuthRule as RuleModel;
use app\admin\model\User as UserModel;
use app\admin\model\Webconfig as WebModel;
use Cache;

class Index extends Base
{

    public function index()
    {

        /**
         * 显示主菜单
         * @var [type]
         */
        $list = cache('DB_TREE_MENU_' . UID);
        if (!$list) {
            $where = [
                'ismenu' => 1,
                'module' => 'admin',
            ];
            //echo UID;
            if (defined(UID) && UID > 1) {
                $where['status'] = 1;
            }

            $list = RuleModel::where($where)->order('sorts ASC,id ASC')->select();
            //判断导航tree用户使用权限
            foreach ($list as $k => $val) {
                if ((self::authcheck($val['name'], UID) == 'noauth') && UID != 1) {
                    //UID 为1的为主管理员 不为验证
                    unset($list[$k]);
                }
            }
            cache('DB_TREE_MENU_' . UID, $list); //设置缓存
        }

        $tree = new \my\Tree();
        $data = $tree->channelLevel($list, 0);

        $web['web'] = WebModel::where('varname', 'web')->value('value'); //网站名称

        $this->assign([
            'lefttree' => $data,
            'web'      => $web,

        ]);
        return $this->fetch();
    }

    /**
     * 显示主页欢迎界面统计信息
     * @return [type] [description]
     */
    public function welcome()
    {
        $web['userCount']    = UserModel::where('tid', 2)->count(); //用户总数
        $web['articleCount'] = ArticleModel::count(); //文章总数

        $web['config'] = $this->systemConfig();              //服务器信息配置

        $this->assign([
            'web' => $web,
        ]);
        return $this->fetch();
    }

    /**
     * @Title: authcheck
     * @Description: todo(权限节点判断)
     * @param string $rule
     * @param int $uid
     * @param string $relation
     * @param string $t
     * @param string $f
     * @return string
     * @author duqiu
     * @date 2016-5-24
     */
    private static function authcheck($rule, $uid, $relation = 'or', $t = '', $f = 'noauth')
    {
        $auth = new \my\Auth();
        if ($auth->check($rule, $uid, $type = 1, $mode = 'url', $relation)) {
            $result = $t;
        } else {
            $result = $f;
        }
        return $result;
    }

    /**
     * @Title: userNear
     * @Description: todo(最近7天注册用户)
     * @date 2017年8月14日
     * @throws
     */
    private static function userNear()
    {
        $nowTime         = strtotime(date('Ymd', time())) + 86400;
        $userTime        = $nowTime - 604800;
        return $userNear = UserModel::where('create_time', 'egt', $userTime)->count();
    }

    /**
     * @Title: loginLogLineJson
     * @Description: todo(最近30天登录统计json)
     * @date 2017年8月14日
     * @throws
     */
    private static function loginLogLineJson()
    {
        $loginLogModel = new \app\admin\model\LoginLog;
        $userModel     = new \app\admin\model\User;

        $nowTime                                       = strtotime(date('Ymd', time())) + 86400;
        $loginLogLineTime                              = $nowTime - 2592000;
        $loginLogLine                                  = $loginLogModel->where('create_time', 'between', [$loginLogLineTime, $nowTime])->select();
        $loginLogLineArr                               = [];
        $loginLogLineArr['datasets'][0]['label']       = lang('login_count');
        $loginLogLineArr['datasets'][0]['fill']        = false;
        $loginLogLineArr['datasets'][0]['borderColor'] = '#4bc0c0';
        foreach ($loginLogLine as $k => $v) {
            $labels = date('Y-m-d', strtotime($v['create_time']));
            if (!in_array($labels, $loginLogLineArr['labels'])) {
                $loginLogLineArr['labels'][] = date('Y-m-d', strtotime($v['create_time']));
            }
            $loginLogLineArr['datasets']['data'][$labels] += 1;
        }
        $old = $loginLogLineArr['datasets']['data'];
        unset($loginLogLineArr['datasets']['data']);
        foreach ($old as $v) {
            $loginLogLineArr['datasets'][0]['data'][] = $v;
        }
        return $loginLogLineJson = json_encode($loginLogLineArr);
    }

    /**
     * @Title: groupPieJson
     * @Description: todo(用户组人数统计)
     * @date 2017年8月14日
     * @throws
     */
    private static function groupPieJson()
    {
        $agModel   = new \app\admin\model\AuthGroup;
        $userModel = new \app\admin\model\User;

        $groupPieArr = [];

        $agData                    = $agModel->where('status', 1)->select();
        $noGroup                   = ['id' => '0', 'title' => '无角色用户', 'pic' => '#666'];
        $agData[count($array) - 1] = $noGroup;
        foreach ($agData as $k => $v) {
            $agData[$k]['count']     = 0;
            $groupPieArr['labels'][] = $v['title'];
        }
        $userData = $userModel->select();
        foreach ($userData as $k => $v) {
            $userGroup = $v->userGroup;
            if (!empty($userGroup)) {
                foreach ($userGroup as $k2 => $v2) {
                    foreach ($agData as $k3 => $v3) {
                        if ($v3['id'] == $v2['group_id']) {
                            $agData[$k3]['count'] += 1;
                            break;
                        }
                    }
                }
            } else {
                $agData[count($array) - 1]['count'] += 1;
            }
        }
        foreach ($agData as $k => $v) {
            $groupPieArr['datasets'][0]['data'][]            = $v['count'];
            $groupPieArr['datasets'][0]['backgroundColor'][] = $v['pic'];
        }
        return $groupPieJson = json_encode($groupPieArr);
    }

    /**
     * @Title: systemConfig
     * @Description: todo(服务器信息配置)
     * @date 2017年8月14日
     * @throws
     */
    private static function systemConfig()
    {
        return $config = [
            '操作系统'    => PHP_OS,
            '服务器时间'   => date("Y-n-j H:i:s"),
            '运行环境'    => $_SERVER["SERVER_SOFTWARE"],
            'PHP运行方式' => php_sapi_name(),
            '上传附件限制'  => ini_get('upload_max_filesize'),
            '执行时间限制'  => ini_get('max_execution_time') . '秒',

        ];
    }

    /**
     * @Title: cleanCache
     * @Description: todo(清除缓存)
     * @author 苏晓信
     * @date 2017年8月14日
     * @throws
     */
    public function cleanCache()
    {
        //if (request()->isPost()) {
        Cache::clear();
        $this->success('清除成功', 'index/index');
        //} else {
        // $this->error('错误', url('index/index'));
        //}
    }

    public function _empty($name)
    {

        $this->city();
        return $this->fetch('common/empty');
    }

    //注意 city方法 本身是 protected 方法
    protected function city()
    {
        //根据当前控制器名来判断要执行那个城市的操作
        $empty['c'] = \Request::controller();
        $empty['a'] = \Request::action();

        $this->assign([
            'e' => $empty,
        ]);
    }

}
